package web;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;

public class LoginPage extends WebPage {
	private static final long serialVersionUID = 1L;
	private String username, password;

	public LoginPage(final PageParameters parameters) {
		Form<Void> form = new Form<Void>("loginform");
		form.add(new RequiredTextField<String>("username",new PropertyModel<String>(this, "username")),
				new PasswordTextField("password", new PropertyModel<String>(this, "password")),
				botonLogin(), new FeedbackPanel("feedback"));
		add(form);
	}

	private Component botonLogin() {
		return new AjaxSubmitLink("login") {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				SpringWicketWebSession session = SpringWicketWebSession.getSpringWicketWebSession();
				if (session.signIn(username, password)) {
					// redirect here
					// info(getString("login.success"));
					if (!continueToOriginalDestination()) {
						setResponsePage(Index.class);
					}
				} else {
					info("login failed");
				}
			}

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {}
		};
	}
}